package com.lenovo.spider;

import com.lenovo.spider.support.cookie.CookieStore;
import com.lenovo.spider.support.cookie.SpiderCookieJar;
import com.lenovo.spider.support.proxy.SpiderProxyPool;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/29 17:05
 */
public enum Context {
    INSTANCE;
    /**
     * 代理管理
     */
    @Getter
    private SpiderProxyPool proxyPool;
    /**
     * cookie管理
     */
    @Getter
    private SpiderCookieJar cookieJar;

    /**
     * 获取爬虫上下文环境
     *
     * @return
     */
    public static Context getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化爬虫上下文环境
     *
     * @return
     */
    public static ContextInitializer init() {
        return new ContextInitializer();
    }


    public static class ContextInitializer {

        /**
         * 设置CookieJar
         *
         * @param factory CookieStore工厂
         * @return
         */
        public ContextInitializer setCookieJar(Supplier<CookieStore> factory) {
            Objects.requireNonNull(factory);
            INSTANCE.cookieJar = new SpiderCookieJar(factory.get());
            return this;
        }

        /**
         * 设置ProxyPool
         *
         * @param proxyPool proxyPool
         * @return
         */
        public ContextInitializer setProxyPool(SpiderProxyPool proxyPool) {
            Objects.requireNonNull(proxyPool);
            INSTANCE.proxyPool = proxyPool;
            return this;
        }

        public Context done() {
            return INSTANCE;
        }
    }
}
